package com.interactiveyang.meet;

import java.util.List;

import oauth.signpost.OAuth;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.signature.HmacSha1MessageSigner;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.google.gson.Gson;

/**
 * The page with the map.
 * @author yangliu
 *
 */
public class MapPage extends MapActivity implements LocationListener, OnSharedPreferenceChangeListener {
	LinearLayout linearLayout;
	MapView mapView;
	
	List<Overlay> mapOverlays;
	Drawable selfMarkerDrawable;
	Drawable othersMarkerDrawable;
	SelfMapMarker selfMarker;
	OthersMapMarker othersMarker;
	
	MapController myMapController;
	
	LocationManager lm;
	
	TextView tv;
	
	BackendRequest backendRequest;
	Gson gson;
	
	public static UserInfoFromJson userInfo;
	
	private SharedPreferences prefs;
	private String token, secret;
	static public String USERNAME;
	private String password;
	
	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        C.setFullScreen(this);
        setContentView(R.layout.mapview);
        
        prefs = main.prefs;
        prefs.registerOnSharedPreferenceChangeListener(this);
        
        token = prefs.getString(OAuth.OAUTH_TOKEN, "");
		secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
        USERNAME = prefs.getString(C.UserInfo.MEET_USERNAME_PREFTITLE, "");
		
        mapView = (MapView) findViewById(R.id.mapview);
        tv = (TextView) findViewById(R.id.TextView01);
		
        tv.setText(getCurrentLocationFromLatitude());
        
        gson = new Gson();
        
        tv.setText(C.MeetBack.backendRequest.getOtherUserInfo(USERNAME));
        
        //	Get the user info from mysql@meet.interactiveyang.com and convert the string to json
        userInfo = gson.fromJson("{'userInfo': " + C.MeetBack.backendRequest.getOtherUserInfo(USERNAME) + "}", UserInfoFromJson.class);
        
//        tv.setText(userInfo.userInfo.get(0).username);
        
//        tv.setText(username);
        
        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000l, 50f, this);
        
        myMapController = mapView.getController();
        myMapController.setZoom(10);
        
        mapOverlays = mapView.getOverlays();
        mapView.setBuiltInZoomControls(true);
       
        selfMarkerDrawable = this.getResources().getDrawable(R.drawable.self_marker);
        othersMarkerDrawable = this.getResources().getDrawable(R.drawable.others_marker);
        selfMarker = new SelfMapMarker(selfMarkerDrawable, mapView);        
        othersMarker = new OthersMapMarker(othersMarkerDrawable, mapView);    
    }
    
    //	TODO put this into a separate thread
    @Override
	public void onLocationChanged(Location paramLocation) {
		int lat = (int) (paramLocation.getLatitude() * 1000000);
		int lan = (int) (paramLocation.getLongitude() * 1000000);
		
		//	Update the current location in mysql
		if(C.MeetBack.backendRequest.saveUserCurrentLocation(paramLocation.getLatitude(), paramLocation.getLongitude(), USERNAME)){
			Toast t = Toast.makeText(this, "save successed!!!", Toast.LENGTH_SHORT);
			t.show();
		}
		else{
			Toast t = Toast.makeText(this, "save failed!!!", Toast.LENGTH_SHORT);
			t.show();
		}
		
		//	Add the self marker onto the map
		GeoPoint startPoint = new GeoPoint(lat, lan);
		
        OverlayItem overlayItem = new OverlayItem(startPoint, USERNAME, "Hey, did someone saw that? She is FengJie!!");
        
        myMapController.animateTo(startPoint);        
        
        selfMarker.updateOverlay(overlayItem);
        mapOverlays.add(selfMarker);
        
        //	Add others' marker onto the map
//        UserInfoFromJson userInfo = gson.fromJson("{'userInfo': " + C.MeetBack.backendRequest.getOtherUserInfo(USERNAME) + "}", UserInfoFromJson.class);
        
        for(int i=0; i<userInfo.userInfo.size(); i++){
        	UserInfo ui = userInfo.userInfo.get(i);
        	GeoPoint otherOPoint = new GeoPoint(ui.current_lat, ui.current_lan);
        	OverlayItem othersOverlayItem = new OverlayItem(otherOPoint, ui.username, "Some thing here");
        	othersMarker.addOverlay(othersOverlayItem);
        	mapOverlays.add(othersMarker);
        }
	}

	@Override
	public void onStatusChanged(String paramString, int paramInt,
			Bundle paramBundle) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderEnabled(String paramString) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderDisabled(String paramString) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
			String key) {
		// TODO Auto-generated method stub
		
	}
	
	public String getCurrentLocationFromLatitude(){
		OAuthConsumer consumer = new CommonsHttpOAuthConsumer(C.OAuth.CONSUMER_KEY, C.OAuth.CONSUMER_SECRET);
		consumer.setMessageSigner(new HmacSha1MessageSigner());
		consumer.setTokenWithSecret(token, secret);
		String dataString = "";
		
		try {
			String url = consumer.sign(C.GLatitude.GET_CURRENT_LOCATION);
			DefaultHttpClient client = new DefaultHttpClient();
			tv.setText(url);
			
			HttpGet get = new HttpGet(C.GLatitude.GET_CURRENT_LOCATION);
			consumer.sign(get);
			
			HttpResponse response = client.execute(get);
			
			if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
				dataString = EntityUtils.toString(response.getEntity());
			}
			
		} 
		catch (Exception e) {
			android.util.Log.e("MEET", "", e);
		}
		
		return dataString;
	}
	
}
